/**
 * 操作日志模拟数据模块
 * 提供操作日志管理的模拟数据
 */

const MockOperationLogsData = (function () {
    // 操作类型
    const OPERATION_TYPES = {
        DEVICE_CONTROL: 'DEVICE_CONTROL'
    };

    // 操作状态
    const OPERATION_STATUS = {
        SUCCESS: 'SUCCESS',
        FAILURE: 'FAILURE',
        PENDING: 'PENDING'
    };

    // 用户列表
    const USERS = ['admin', 'operator', 'viewer', 'manager'];

    // 设备类型
    const DEVICE_TYPES = ['轴流风机', '环流风机', '自然通风窗', '轴流通风窗', '环流通风窗'];

    // 页面列表
    const PAGES = ['智能通风', '气体监测', '粮情检测', '能耗监测', '设备管理', '用户管理', '系统设置'];

    // 生成操作日志数据
    let operationLogs = [];
    let logIdCounter = 1;

    /**
     * 生成随机时间戳（最近30天内）
     */
    function generateRandomTimestamp() {
        const now = Date.now();
        const thirtyDaysAgo = now - (30 * 24 * 60 * 60 * 1000);
        return Math.floor(Math.random() * (now - thirtyDaysAgo)) + thirtyDaysAgo;
    }

    /**
     * 格式化时间字符串
     */
    function formatTimeString(timestamp) {
        const date = new Date(timestamp);
        return date.getFullYear() + '-' + 
               String(date.getMonth() + 1).padStart(2, '0') + '-' + 
               String(date.getDate()).padStart(2, '0') + ' ' + 
               String(date.getHours()).padStart(2, '0') + ':' + 
               String(date.getMinutes()).padStart(2, '0') + ':' + 
               String(date.getSeconds()).padStart(2, '0');
    }

    /**
     * 生成设备控制日志
     */
    function generateDeviceControlLog() {
        const username = USERS[Math.floor(Math.random() * USERS.length)];
        const deviceType = DEVICE_TYPES[Math.floor(Math.random() * DEVICE_TYPES.length)];
        const deviceId = Math.floor(Math.random() * 10) + 1;
        const actions = ['开启', '关闭', '停止', '重启'];
        const action = actions[Math.floor(Math.random() * actions.length)];
        const isSuccess = Math.random() > 0.1; // 90%成功率
        const timestamp = generateRandomTimestamp();

        return {
            id: logIdCounter++,
            username: username,
            operationType: OPERATION_TYPES.DEVICE_CONTROL,
            operationDescription: `${action}${deviceType}设备`,
            operationPage: '智能通风',
            operationTarget: `设备ID: ${deviceId}`,
            operationStatus: isSuccess ? OPERATION_STATUS.SUCCESS : OPERATION_STATUS.FAILURE,
            errorMessage: isSuccess ? null : `设备${deviceId}响应超时`,
            operationTime: timestamp,
            operationTimeString: formatTimeString(timestamp),
            ipAddress: `192.168.1.${Math.floor(Math.random() * 200) + 1}`,
            userAgent: 'Mozilla/5.0 (Android 10; Mobile; rv:81.0) Gecko/81.0 Firefox/81.0'
        };
    }

    /**
     * 初始化操作日志数据
     */
    function initializeData() {
        operationLogs = [];
        logIdCounter = 1;

        // 生成不同类型的日志，总共200条
        for (let i = 0; i < 200; i++) {
            const log = generateDeviceControlLog();
            operationLogs.push(log);
        }

        // 按时间倒序排列
        operationLogs.sort((a, b) => b.operationTime - a.operationTime);
    }

    /**
     * 获取操作日志列表（分页）
     */
    function getOperationLogs(page = 1, pageSize = 20, filters = {}) {
        let filteredLogs = [...operationLogs];

        // 应用筛选条件
        if (filters.operationType) {
            filteredLogs = filteredLogs.filter(log => log.operationType === filters.operationType);
        }

        if (filters.operationStatus) {
            filteredLogs = filteredLogs.filter(log => log.operationStatus === filters.operationStatus);
        }

        if (filters.username) {
            filteredLogs = filteredLogs.filter(log => 
                log.username.toLowerCase().includes(filters.username.toLowerCase())
            );
        }

        if (filters.keyword) {
            filteredLogs = filteredLogs.filter(log => 
                log.operationDescription.toLowerCase().includes(filters.keyword.toLowerCase()) ||
                log.operationTarget.toLowerCase().includes(filters.keyword.toLowerCase())
            );
        }

        if (filters.startDate && filters.endDate) {
            const startTime = new Date(filters.startDate).getTime();
            const endTime = new Date(filters.endDate).getTime() + 24 * 60 * 60 * 1000; // 包含结束日期整天
            filteredLogs = filteredLogs.filter(log => 
                log.operationTime >= startTime && log.operationTime < endTime
            );
        }

        // 计算分页
        const totalCount = filteredLogs.length;
        const totalPages = Math.ceil(totalCount / pageSize);
        const startIndex = (page - 1) * pageSize;
        const endIndex = Math.min(startIndex + pageSize, totalCount);
        const logs = filteredLogs.slice(startIndex, endIndex);

        return {
            success: true,
            data: {
                list: logs,
                totalCount: totalCount,
                totalPages: totalPages,
                currentPage: page,
                pageSize: pageSize,
                hasPrevious: page > 1,
                hasNext: page < totalPages
            }
        };
    }

    /**
     * 添加操作日志
     */
    function addOperationLog(logData) {
        const timestamp = Date.now();
        const log = {
            id: logIdCounter++,
            username: logData.username || 'unknown',
            operationType: OPERATION_TYPES.DEVICE_CONTROL,
            operationDescription: logData.operationDescription || '',
            operationPage: logData.operationPage || '',
            operationTarget: logData.operationTarget || '',
            operationStatus: logData.operationStatus || OPERATION_STATUS.SUCCESS,
            errorMessage: logData.errorMessage || null,
            operationTime: timestamp,
            operationTimeString: formatTimeString(timestamp),
            ipAddress: logData.ipAddress || '192.168.1.100',
            userAgent: logData.userAgent || 'Mock User Agent'
        };

        operationLogs.unshift(log); // 添加到开头
        
        return {
            success: true,
            message: '操作日志记录成功'
        };
    }

    // 初始化数据
    initializeData();

    // 暴露公共方法
    return {
        getOperationLogs,
        addOperationLog,
        initializeData,
        OPERATION_TYPES,
        OPERATION_STATUS
    };
})();

// 如果在浏览器环境中，将模块添加到全局对象
if (typeof window !== 'undefined') {
    window.MockOperationLogsData = MockOperationLogsData;
} 